package com.itheima.controller;

import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;



    @GetMapping
    public Result selectAll() {
        List<User> userList = userService.selectAll();

        Integer code = userList==null?Code.SELECT_ERR:Code.SELECT_ERR;

        String mes= userList==null?"数据查询失败，请重新再试":"";

        return new Result(code,userList,mes);
    }

    @GetMapping("/{id}")
    public Result selectById(@PathVariable int id) {

        User user = userService.selectById(id);

        Integer code = user==null?Code.SELECT_ERR:Code.SELECT_OK;

        String mes= user==null?"数据查询失败，请重新再试":"";

        return new Result(code,user,mes);
    }

    @PostMapping
    public Result add(@RequestBody User user) {


        boolean flag = userService.add(user);

        return new Result(flag?Code.ADD_OK:Code.ADD_ERR,flag);

    }

    @PutMapping
    public Result update(@RequestBody User user) {


        System.out.println(user);

        boolean flag = userService.update(user);

        return new Result(flag?Code.UPDATE_OK:Code.UPDATE_ERR,flag);

    }

    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable int id) {
        boolean flag = userService.deleteById(id);
        return new Result(flag?Code.DELETE_OK:Code.DELETE_ERR,flag);

    }
}
